/**
 * 地图导航工具类（安卓专用，带地图选择器）
 * 支持高德、百度、腾讯地图的导航功能
 */
export default class MapNavigation {
	/**
	 * 开始导航（主方法）
	 * @param {Object} startPoint - 起点信息
	 * @param {number} startPoint.latitude - 起点纬度
	 * @param {number} startPoint.longitude - 起点经度
	 * @param {string} startPoint.name - 起点名称
	 * @param {Object} endPoint - 终点信息
	 * @param {number} endPoint.latitude - 终点纬度
	 * @param {number} endPoint.longitude - 终点经度
	 * @param {string} endPoint.name - 终点名称
	 * @param {string} [navigationType='drive'] - 导航类型 ('drive'|'walk'|'bike'|'transit')
	 */
	static navigate(startPoint, endPoint, navigationType = 'drive') {
		if (!endPoint || !endPoint.latitude || !endPoint.longitude) {
			return Promise.reject(new Error('缺少终点坐标信息'));
		}

		if (!startPoint || !startPoint.latitude || !startPoint.longitude) {
			return Promise.reject(new Error('缺少起点坐标信息'));
		}

		return this._showMapSelector(startPoint, endPoint, navigationType);
	}

	/**
	 * 显示地图选择器
	 */
	static _showMapSelector(startPoint, endPoint, navigationType) {
		return new Promise((resolve, reject) => {
			uni.showActionSheet({
				itemList: ['高德地图', '百度地图', '腾讯地图'],
				success: (res) => {
					const mapApps = ['gaode', 'baidu', 'tencent'];
					const selectedMap = mapApps[res.tapIndex];

					if (selectedMap) {
						const mapMethods = {
							'gaode': this._navigateWithGaode,
							'baidu': this._navigateWithBaidu,
							'tencent': this._navigateWithTencent
						};

						mapMethods[selectedMap].call(this, startPoint, endPoint, navigationType)
							.then(resolve)
							.catch(reject);
					} else {
						resolve(null); // 用户取消
					}
				},
				fail: (err) => reject(err)
			});
		});
	}

	/**
	 * 使用高德地图导航
	 */
	static _navigateWithGaode(startPoint, endPoint, navigationType) {
		return new Promise((resolve, reject) => {
			const typeMap = {
				'drive': 0, // 驾车
				'walk': 1, // 步行
				'bike': 2, // 骑行
				'transit': 3 // 公交
			};

			const type = typeMap[navigationType] || 0;

			// 备选URI格式，提高兼容性
			const urls = [
				`amapuri://route/plan/?dlat=${endPoint.latitude}&dlon=${endPoint.longitude}&dname=${encodeURIComponent(endPoint.name)}&slat=${startPoint.latitude}&slon=${startPoint.longitude}&sname=${encodeURIComponent(startPoint.name)}&dev=0&t=${type}`,
				`androidamap://route?sourceApplication=appname&slat=${startPoint.latitude}&slon=${startPoint.longitude}&sname=${encodeURIComponent(startPoint.name)}&dlat=${endPoint.latitude}&dlon=${endPoint.longitude}&dname=${encodeURIComponent(endPoint.name)}&dev=0&t=${type}`
			];

			const tryOpenUrl = (index = 0) => {
				if (index >= urls.length) {
					reject(new Error('无法打开高德地图'));
					return;
				}

				// 使用plus.runtime.openURL替代uni.navigateToUrl
				this._openUrl(urls[index])
					.then(resolve)
					.catch(() => tryOpenUrl(index + 1));
			};

			tryOpenUrl();
		});
	}

	/**
	 * 使用百度地图导航
	 */
	static _navigateWithBaidu(startPoint, endPoint, navigationType) {
		return new Promise((resolve, reject) => {
			// 转换坐标（百度地图使用BD-09坐标系）
			const startBD = this._gcj02ToBd09(startPoint.latitude, startPoint.longitude);
			const endBD = this._gcj02ToBd09(endPoint.latitude, endPoint.longitude);

			const typeMap = {
				'drive': 'driving',
				'walk': 'walking',
				'bike': 'riding',
				'transit': 'transit'
			};

			const type = typeMap[navigationType] || 'driving';
			const url =
				`baidumap://map/direction?origin=name:${encodeURIComponent(startPoint.name)}|latlng:${startBD.lat},${startBD.lng}&destination=name:${encodeURIComponent(endPoint.name)}|latlng:${endBD.lat},${endBD.lng}&mode=${type}&coord_type=bd09ll&src=andr.uni-app.demo`;

			// 使用plus.runtime.openURL替代uni.navigateToUrl
			this._openUrl(url)
				.then(resolve)
				.catch((err) => {
					console.error('打开百度地图失败:', err);
					uni.showToast({
						title: '未安装百度地图或无法打开',
						icon: 'none'
					});
					reject(err);
				});
		});
	}

	/**
	 * 使用腾讯地图导航
	 */
	static _navigateWithTencent(startPoint, endPoint, navigationType) {
		return new Promise((resolve, reject) => {
			const typeMap = {
				'drive': 'drive',
				'walk': 'walk',
				'bike': 'bike',
				'transit': 'bus'
			};

			const type = typeMap[navigationType] || 'drive';
			const url =
				`qqmap://map/routeplan?type=${type}&from=${encodeURIComponent(startPoint.name)}&fromcoord=${startPoint.latitude},${startPoint.longitude}&to=${encodeURIComponent(endPoint.name)}&tocoord=${endPoint.latitude},${endPoint.longitude}&policy=0&referer=UNIAPPDEMO`;

			// 使用plus.runtime.openURL替代uni.navigateToUrl
			this._openUrl(url)
				.then(resolve)
				.catch((err) => {
					console.error('打开腾讯地图失败:', err);
					uni.showToast({
						title: '未安装腾讯地图或无法打开',
						icon: 'none'
					});
					reject(err);
				});
		});
	}

	/**
	 * 打开URL的统一方法
	 */
	static _openUrl(url) {
		return new Promise((resolve, reject) => {
			// 检查是否在App环境中
			if (typeof plus !== 'undefined' && plus.runtime) {
				plus.runtime.openURL(url, (err) => {
					if (err) {
						console.error('打开URL失败:', err);
						reject(err);
					} else {
						resolve(true);
					}
				});
			} else {
				// 非App环境，回退到uni.navigateToUrl
				uni.navigateToUrl({
					url,
					success: () => resolve(true),
					fail: (err) => reject(err)
				});
			}
		});
	}

	/**
	 * GCJ-02 转换为 BD-09（百度地图坐标）
	 */
	static _gcj02ToBd09(lat, lng) {
		const x_pi = 3.14159265358979324 * 3000.0 / 180.0;
		const x = lng;
		const y = lat;
		const z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
		const theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
		const bd_lng = z * Math.cos(theta) + 0.0065;
		const bd_lat = z * Math.sin(theta) + 0.006;
		return {
			lat: bd_lat,
			lng: bd_lng
		};
	}
}